package cn.mumzone.basic.net.http.callback;

import com.google.gson.JsonSyntaxException;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.ConnectException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import cn.mumzone.basic.net.response.BaseResponse;
import cn.mumzone.basic.util.log.Elog;


/**
 * Author Chaney
 * Date   2017/3/7 上午11:28.
 * EMail  qiuzhenhuan.hi@gmail.com
 */
public abstract class ApiCallBack<T> extends CallBack<T> {

    public static final int CODE_NET_ERROR = -101;

    @Override
    public abstract void onSuccess(T t);

    @Override
    public abstract void onError(BaseResponse response);

    public void onNetworkError(BaseResponse response) {
    }

    @Override
    public void onError(Throwable e) {
        BaseResponse response = new BaseResponse();
        if (e instanceof SocketTimeoutException) {
            Elog.e("Retrofit", "请求超时");
            response.setCode(CODE_NET_ERROR);
            response.setMsg("网络连接超时");
        } else if (e instanceof ConnectException) {
            Elog.e("Retrofit", "连接异常");
            response.setMsg("网络连接失败");
            response.setCode(CODE_NET_ERROR);
        } else if (e instanceof SocketException) {
            Elog.e("Retrofit", "连接异常");
            response.setMsg("网络连接失败");
            response.setCode(CODE_NET_ERROR);
        }else if (e instanceof UnknownHostException) {
            Elog.e("Retrofit", "无网络连接");
            response.setMsg("网络连接失败");
            response.setCode(CODE_NET_ERROR);
        } else if (e instanceof JsonSyntaxException) {
            Elog.e("Retrofit", "数据解析异常");
            response.setMsg("数据解析异常");
        } else {
            response.setMsg("请求失败");
            Elog.e("Retrofit", String.format("抛出异常 : %s", printExceptionInfo(e)));
        }
        printExceptionInfo(e);
        e.printStackTrace();

        onError(response);
        if (response.getCode() == CODE_NET_ERROR) {
            onNetworkError(response);
        }

    }

    private String printExceptionInfo(Throwable e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        e.printStackTrace(pw);
        pw.flush();
        sw.flush();
        return sw.toString();
    }

    @Override
    protected void onParseError(String msg) {
        BaseResponse response = new BaseResponse();
        response.setMsg(msg);
        onError(response);
    }
}
